
interface Window {
  //task任务的即间隔长度
  customerTaskWorkTimeLen: number,
  // task任务的id
  customerWorkTaskIntervalId: number | undefined,
  //任务检索表
  taskMap: Map<string, number> | null | undefined,



  //添加任务
  pushLoopTask: Function,
  //添加任务集合
  pushLoopTaskList: Function,
  //执行任务
  executeLoopTask: Function,
  //Task任务执行程序
  // createdLoopTask: Function,
  //清楚任务
  clearTask: Function,
}

declare const window: any;


export default () => {

  /**
   * 任务参数
   */
  interface TaskInfo {
    method: Function,
    immediate: boolean,
    interval: number,
    name: string
  }


  /**
   * 获取最小定时间隔，进行使用，节省资源
   */
  window.customerTaskWorkTimeLen = 2000;
  function getMinCustomerTaskWorkTimeLen(): number {
    const timeLen: Array<number> = loopTaskList.map(item => item.interval);
    const minTimeLen: number = Math.min(...timeLen) || 2000;

    if (window.customerTaskWorkTimeLen !== minTimeLen) {
      clearInterval(window.customerWorkTaskIntervalId);
      window.customerTaskWorkTimeLen = minTimeLen;
      createdLoopTask();
    }
    return minTimeLen;
  }

  /**
   * method:function, //执行函数
   * immediate:boolean, //是否立即执行
   * interval:number //定时间隔
   * name:string //定时任务名称，确保任务的唯一性
   */
  let loopTaskList: Array<TaskInfo> = [];
  window.customerWorkTaskIntervalId = undefined;



  /**
   * 添加键值对，记录定时任务信息，确保定时任务不重复
   */
  let taskMap = window.taskMap || {};

  function getTaskByMap(task: TaskInfo) {
    if (!task.name || task.name == 'undefined') {
      console.error('必须设置任务名称，确保任务的唯一性');
    }
    const index = taskMap[task.name || task.method.name];
    if (index || index == 0) { //已存在，移除旧的，添加新的
      loopTaskList = loopTaskList.filter((item, _index) => index != _index);
      console.log("替换任务：" + task.name || task.method.name);
    } else {
      console.log("添加任务：" + task.name || task.method.name);
    }
    loopTaskList.push(task);
    taskMap = {};
    loopTaskList.map((item, index) => {
      taskMap[task.name || task.method.name] = index;
    });
  }

  /**
   * 创建Task任务
   */
  let createdLoopTask = function (): void {
    console.log(window.customerTaskWorkTimeLen);
    let count = 0;
    clearInterval(window.customerWorkTaskIntervalId);
    window.customerWorkTaskIntervalId = setInterval(() => {
      console.log(new Date().getTime(), window.customerTaskWorkTimeLen);
      loopTaskList.map(item => {
        const times = Math.ceil(item.interval / window.customerTaskWorkTimeLen);
        const immediate = item.immediate;
        if (immediate || (count % times == 0 && count > 0)) {
          try {
            if (typeof item.method == 'function') {
              item.method();
            }
          } catch (error) {
            console.error(error);
          }
          item.immediate = false;
        }
      })
      count++;
    }, window.customerTaskWorkTimeLen);
  }
  /**
   * 添加定时任务到列表
   * @param {Object} _loopTaskList 
   */
  window.pushLoopTask = window.pushLoopTask || function (_loopTask: TaskInfo) {
    getTaskByMap(_loopTask);
    getMinCustomerTaskWorkTimeLen();
  }
  /**
    * 添加定时任务到列表
    * @param {Array} _loopTaskList 
    */
  window.pushLoopTaskList = window.pushLoopTaskList || function (_loopTaskList: Array<TaskInfo>) {
    _loopTaskList.map(item => {
      getTaskByMap(item);
    })
    getMinCustomerTaskWorkTimeLen();
  }

  /**
   * 执行定时任务
   * @returns 
   */
  window.executeLoopTask = window.executeLoopTask || function (isStart = false) {
    clearInterval(window.customerWorkTaskIntervalId);
    if (!isStart) {
      return;
    }
    console.log('开始任务,任务数量：', loopTaskList.length, '时间：' + new Date());
    getMinCustomerTaskWorkTimeLen();
    createdLoopTask();
  }

  window.clearTask = window.clearTask || function () {
    clearInterval(window.customerWorkTaskIntervalId);
    console.log('结束任务,任务数量：', loopTaskList.length, '时间：' + new Date());
    loopTaskList = [];
  }

  return {
    pushLoopTask: window.pushLoopTask,
    pushLoopTaskList: window.pushLoopTaskList,
    executeLoopTask: window.executeLoopTask,
    clearTask: window.clearTask,
  }
}
